﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Dynamic;
using System.Linq;

namespace Viyi.Util.Data
{
    public class DynamicDataRow : DynamicObject
    {
        private readonly DataRow dataRow;

        public DynamicDataRow(DataRow dataRow)
        {
            this.dataRow = dataRow;
        }

        public override IEnumerable<string> GetDynamicMemberNames()
        {
            return dataRow.Table.Columns
                .OfType<DataColumn>()
                .Select(column => column.ColumnName);
        }

        public override bool TryGetMember(GetMemberBinder binder, out object result)
        {
            try
            {
                result = dataRow[binder.Name];

                if (result == DBNull.Value)
                {
                    result = binder.ReturnType.IsValueType
                        ? Activator.CreateInstance(binder.ReturnType)
                        : null;
                }

                return true;
            }
            catch
            {
                result = null;
                return false;
            }
        }

        public override bool TrySetMember(SetMemberBinder binder, object value)
        {
            try
            {
                dataRow[binder.Name] = value ?? DBNull.Value;
                return true;
            }
            catch
            {
                return false;
            }
        }
    }
}
